#include "ads8684.h"

#include "std.h"

t_ads8684 ads8684_dev;

void ads8684_init(p_ads8684 dev, uint8_t chan, SPI_HandleTypeDef *spix, GPIO_TypeDef *gpio_cs, uint16_t gpio_pin_cs, GPIO_PinState cs_valid)
{
    dev->chan = chan;

    dev->spix = spix;

    dev->gpio_cs = gpio_cs;
    dev->gpio_pin_cs = gpio_pin_cs;
    dev->cs_valid = cs_valid;
}

int ads8684_read(p_ads8684 dev, uint8_t ch)
{
    int tmp;
    uint8_t tx_buf[5], rx_buf[5];

    HAL_GPIO_WritePin(dev->gpio_cs, dev->gpio_pin_cs, dev->cs_valid);

    tx_buf[0] = ADS8698_CMD_REG_MAN_CH(ch);
    tx_buf[1] = 0x00;
    tx_buf[2] = 0x00;
    tx_buf[3] = 0x00;
    tx_buf[4] = 0x00;

    tmp = HAL_SPI_TransmitReceive(dev->spix, tx_buf, rx_buf, 5, 1000);
    if (tmp == HAL_OK)
    {
        dev->data[ch] = (rx_buf[2] << 8) | (rx_buf[3]);
    }

    HAL_GPIO_WritePin(dev->gpio_cs, dev->gpio_pin_cs, (GPIO_PinState)(!(dev->cs_valid)));

    return tmp;
}

static int ads8698_prog_read(p_ads8684 dev, uint8_t addr, uint8_t *val)
{
    int tmp;
    uint8_t tx_buf[3], rx_buf[3];

    HAL_GPIO_WritePin(dev->gpio_cs, dev->gpio_pin_cs, dev->cs_valid);

    tx_buf[0] = (addr << 1) | ADS8698_PROG_R_BIT;
    tx_buf[1] = 0x00;
    tx_buf[2] = 0x00;

    tmp = HAL_SPI_TransmitReceive(dev->spix, tx_buf, rx_buf, 3, 1000);
    if (tmp == HAL_OK)
    {
        *val = rx_buf[2];
    }

    HAL_GPIO_WritePin(dev->gpio_cs, dev->gpio_pin_cs, (GPIO_PinState)(!(dev->cs_valid)));

    return tmp;
}

static int ads8698_prog_write(p_ads8684 dev, uint8_t addr, uint8_t val)
{
    int tmp;
    uint8_t tx_buf[3], rx_buf[3];

    HAL_GPIO_WritePin(dev->gpio_cs, dev->gpio_pin_cs, dev->cs_valid);

    tx_buf[0] = (addr << 1) | ADS8698_PROG_W_BIT;
    tx_buf[1] = val;
    tx_buf[2] = 0x00;

    tmp = HAL_SPI_TransmitReceive(dev->spix, tx_buf, rx_buf, 3, 1000);
    if (tmp == HAL_OK)
    {
    }

    HAL_GPIO_WritePin(dev->gpio_cs, dev->gpio_pin_cs, (GPIO_PinState)(!(dev->cs_valid)));

    return tmp;
}

int ads8698_reset(p_ads8684 dev)
{
    int tmp;
    uint8_t rxval;
    uint8_t tx_buf[4], rx_buf[4];

    HAL_GPIO_WritePin(dev->gpio_cs, dev->gpio_pin_cs, dev->cs_valid);

    tx_buf[0] = ADS8698_CMD_REG_RST;
    tx_buf[1] = 0x00;
    tx_buf[2] = 0x00;
    tx_buf[3] = 0x00;

    tmp = HAL_SPI_TransmitReceive(dev->spix, tx_buf, rx_buf, 4, 1000);
    if (tmp == HAL_OK)
    {
    }

    HAL_GPIO_WritePin(dev->gpio_cs, dev->gpio_pin_cs, (GPIO_PinState)(!(dev->cs_valid)));

    ads8698_prog_write(dev, 0x03, 0x01);

    ads8698_prog_read(dev, 0x03, &rxval);

    // printf("Feature Select = %hu\n", rxval);
    return tmp;
}
